import type { Component } from 'vue'
import type { Entity } from '../base'
import IdFilter from './IdFilter.vue'

export type EntityTableCellValue = string | boolean | number

export interface EntityTableColumn<T extends Entity> {
  name: string
  cell: (t: T) => EntityTableCellValue
  width: number
}

export interface EntityTableDefinition<T extends Entity> {
  type: string
  filter: Component
  columns: EntityTableColumn<T>[]
  onDClick?: (id: string) => void
}

export interface EntityFilterInstance<T extends Entity> {
  filter(lst: T[]): T[]
}

const tables: Record<string, EntityTableDefinition<Entity>> = {}

export interface EntityTableOptions<T extends Entity> {
  type: string
  filter?: Component
  columns?: EntityTableColumn<T>[]
  onDClick?: (id: string) => void
}

export function registerEntityTable<T extends Entity>(opts: EntityTableOptions<T>) {
  const def = Object.assign(
    {
      filter: IdFilter,
      columns: [idColumn]
    },
    opts
  ) as EntityTableDefinition<Entity>
  if (!def.type) {
    throw Error('registerTableDefinition: opts.type required!!')
  }
  tables[def.type] = def
}

export function getTableDefinition<T extends Entity>(type: string): EntityTableDefinition<T> {
  const def = tables[type]
  if (!def) {
    return {
      type,
      filter: IdFilter,
      columns: [idColumn]
    }
  }
  return def as EntityTableDefinition<T>
}

const idColumn: EntityTableColumn<Entity> = {
  name: 'id',
  cell: (e: Entity) => e.id,
  width: 100
}
